package com.itheima.reggie.controller;

/**
 * @author mff
 * @date 2022/6/11 15:16
 * @mood happy
 */

import cn.hutool.core.io.IoUtil;
import com.itheima.reggie.common.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.couchbase.CouchbaseProperties;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.UUID;

/**
 * 用于图片的上传与下载
 */
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.path}")
    private String batePath;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
//        获得原始文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

//          防止重名
        String newFileName = UUID.randomUUID().toString() + suffix;
//        创建一个保存目录
        File dir = new File(batePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

//        转存文件
        try {
            file.transferTo(new File(batePath + newFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(newFileName);
    }


//    下载功能

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try {
//        获得输入输出流
            FileInputStream fileInputStream = new FileInputStream(new File(batePath+name));
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("image/jpeg");

            //核心功能
            IoUtil.copy(fileInputStream, outputStream);


            fileInputStream.close();
            outputStream.close();
//        拷贝
        } catch (IOException e) {


        }

    }

}
